﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.BLL;
using WHC.Hotel.Entity;
using WHC.OrderWater.Commons;

namespace WHC.Hotel.UI
{
    public partial class FrmCostAnalyze : BaseForm
    {
        public FrmCostAnalyze()
        {
            InitializeComponent();
        }

        private void InitItem()
        {
            this.txtSearchWareHouse.Items.Clear();
            this.txtSearchWareHouse.Items.AddRange(DictItemUtil.GetWareHouse(true));
            this.txtSearchWareHouse.SelectedIndex = 0;

            this.txtDept.Items.Clear();
            this.txtDept.Items.AddRange(DictItemUtil.GetWareHouse(true));
            this.txtDept.SelectedIndex = 0;
            
            this.dtStart.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            this.dtEnd.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
            
            this.dtTradeStart.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            this.dtTradeEnd.Value = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 23:59:59"));
        }

        private void FrmCostAnalyze_Load(object sender, EventArgs e)
        {
            InitItem();
            this.winGridView1.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView1.AppendedMenu = this.contextMenuStrip1;

            this.winGridView2.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView2.AppendedMenu = this.contextMenuStrip2;
            this.winGridView2.dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
            this.winGridView2.dataGridView1.RowEnter += new DataGridViewCellEventHandler(dataGridView1_RowEnter);

            this.winGridView3.ProgressBar = this.toolStripProgressBar1.ProgressBar;
            this.winGridView3.AppendedMenu = this.contextMenuStrip3;
        }

        private void BindCostData()
        {
            this.winGridView1.DisplayColumns = "ItemNo,ItemName,UnitName,UnitCost,AveragePrice,Quantity,CostAmount,Amount,Profit";

            #region 添加别名解析
            this.winGridView1.AddColumnAlias("ItemNo", "项目编号");
            this.winGridView1.AddColumnAlias("ItemName", "项目名称");
            this.winGridView1.AddColumnAlias("UnitName", "单位");
            this.winGridView1.AddColumnAlias("UnitCost", "单位成本");
            this.winGridView1.AddColumnAlias("AveragePrice", "平均售价");
            this.winGridView1.AddColumnAlias("Quantity", "销售数量");
            this.winGridView1.AddColumnAlias("CostAmount", "销售成本");
            this.winGridView1.AddColumnAlias("Amount", "销售额");
            this.winGridView1.AddColumnAlias("Profit", "毛利");
            #endregion

            SearchCondition condition = new SearchCondition();
            condition.AddCondition("BeginTime", this.dtStart.Value.ToString(), SqlOperator.MoreThanOrEqual)
                .AddCondition("BeginTime", this.dtEnd.Value.ToString(), SqlOperator.LessThanOrEqual)
                .AddCondition("GoodsType", this.txtGoodsType.Text, SqlOperator.Like);
            string filter = condition.BuildConditionSql(DatabaseType.SqlServer);

            DataTable dt = new DataTable();
            if (this.txtSearchWareHouse.Text == "客房仓库")
            {
                dt = BLLFactory<ConsumerList>.Instance.GetCostAnalyzeReport(filter);
            }
            else if (this.txtSearchWareHouse.Text == "KTV仓库")
            {
                dt = BLLFactory<KTVConsumerList>.Instance.GetCostAnalyzeReport(filter);
            }
            else if (this.txtSearchWareHouse.Text == "茶室仓库")
            {
                dt = BLLFactory<TeaConsumerList>.Instance.GetCostAnalyzeReport(filter);
            }
            else
            {
                dt = BLLFactory<ConsumerList>.Instance.GetCostAnalyzeReport(filter);
                DataTable ktvdt = BLLFactory<KTVConsumerList>.Instance.GetCostAnalyzeReport(filter);
                DataTable teadt = BLLFactory<KTVConsumerList>.Instance.GetCostAnalyzeReport(filter);
                dt.Merge(ktvdt);
                dt.Merge(teadt);
            }

            decimal CostAmount = 0M;
            decimal Amount = 0M;
            decimal Profit = 0M;
            foreach (DataRow row in dt.Rows)
            {
                CostAmount += Convert.ToDecimal(row["CostAmount"]);
                Amount += Convert.ToDecimal(row["Amount"]);
                Profit += Convert.ToDecimal(row["Profit"]);
            }
            dt.Rows.Add(dt.NewRow());
            dt.Rows.Add(dt.NewRow());
            DataRow dr = dt.NewRow();
            dr["CostAmount"] = CostAmount;
            dr["Amount"] = Amount;
            dr["Profit"] = Profit;
            dt.Rows.Add(dr);

            this.winGridView1.DataSource = dt.DefaultView;
            this.winGridView1.PrintTitle = Portal.gc.gAppUnit + " -- " + "成本核算报表";
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            BindCostData();
        }

        private void txtSearchWareHouse_SelectedIndexChanged(object sender, EventArgs e)
        {
            CListItem item = txtSearchWareHouse.SelectedItem as CListItem;
            this.txtGoodsType.Items.Clear();
            if (item != null && !string.IsNullOrEmpty(item.Value))
            {
                if (item.Value == "客房仓库")
                {
                    List<GoodsTypeInfo> list = BLLFactory<GoodsType>.Instance.GetAll();
                    foreach (GoodsTypeInfo info in list)
                    {
                        this.txtGoodsType.Items.Add(new CListItem(info.GoodsType));
                    }
                }
                else if (item.Value == "KTV仓库")
                {
                    List<KTVGoodsTypeInfo> list = BLLFactory<KTVGoodsType>.Instance.GetAll();
                    foreach (KTVGoodsTypeInfo info in list)
                    {
                        this.txtGoodsType.Items.Add(new CListItem(info.GoodsType));
                    }
                }
                else if (item.Value == "茶室仓库")
                {
                    List<TeaGoodsTypeInfo> list = BLLFactory<TeaGoodsType>.Instance.GetAll();
                    foreach (TeaGoodsTypeInfo info in list)
                    {
                        this.txtGoodsType.Items.Add(new CListItem(info.GoodsType));
                    }
                }
            }
            this.txtGoodsType.Items.Insert(0, new CListItem("所有项目", ""));
            BindCostData();
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.winGridView2.dataGridView1.Columns.Count > 0)
            {
                this.winGridView2.dataGridView1.Columns[0].Width = 400;
                this.winGridView2.dataGridView1.Columns[1].Width = 200;
            }

            DataGridViewRow row;
            for (int i = 0; i < winGridView2.dataGridView1.Rows.Count; i++)
            {
                row = winGridView2.dataGridView1.Rows[i];
                string prefix = "          ";
                string ItemName = row.Cells["ItemName"].Value.ToString();
                if (!ItemName.Contains(prefix))
                {
                    row.DefaultCellStyle.ForeColor = Color.Red;
                }
            }
        }

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindTradeDetail();
        }

        private void BindTradeData()
        {
            this.winGridView2.DisplayColumns = "ItemName,TotalAmount";

            #region 添加别名解析
            this.winGridView2.AddColumnAlias("ItemName", "项目名称          ");
            this.winGridView2.AddColumnAlias("TotalAmount", "累计金额（元）");
            #endregion

            #region 计算销售收入和成本
		            
            Dictionary<string, decimal> dictAmount = new Dictionary<string, decimal>();
            if (this.txtDept.Text == "客房仓库")
            {
                dictAmount = BLLFactory<RoomBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
            }
            else if (this.txtDept.Text == "KTV仓库")
            {
                dictAmount = BLLFactory<KTVSuiteBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
            }
            else if (this.txtDept.Text == "茶室仓库")
            {
                dictAmount = BLLFactory<TeaSuiteBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
            }
            else
            {
                dictAmount = BLLFactory<RoomBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                Dictionary<string, decimal> ktvDict = BLLFactory<KTVSuiteBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                Dictionary<string, decimal> teaDict = BLLFactory<TeaSuiteBill>.Instance.GetTradeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                foreach (string key in ktvDict.Keys)
                {
                    dictAmount.Add(key, ktvDict[key]);
                }
                foreach (string key in teaDict.Keys)
                {
                    dictAmount.Add(key, teaDict[key]);
                }
            } 

	        #endregion

            #region 计算采购支出
            Dictionary<string, decimal> purchaseDict = BLLFactory<PurchaseHeader>.Instance.GetFeeAmount(this.dtTradeStart.Value, this.dtTradeEnd.Value, this.txtDept.Text);
            foreach (string key in purchaseDict.Keys)
            {
                dictAmount.Add(key, purchaseDict[key]);
            } 
            #endregion

            #region 计算总收入，总成本，利润，利润率
            decimal Amount = 0M;
            decimal CostAmount = 0M;
            foreach (string key in dictAmount.Keys)
            {
                if (dictAmount[key] > 0)
                {
                    Amount += dictAmount[key];
                }
                else
                {
                    CostAmount += dictAmount[key];
                }
            }
            decimal Profit = Amount + CostAmount;//利润
            decimal ProfitRate = 0M;//利润率
            if (Amount != 0M)
            {
                ProfitRate = Profit / Amount;
            } 
            #endregion

            #region 排列显示
            DataTable dt = Portal.gc.CreateTable("ItemName,TotalAmount").Tables[0];
            DataRow row = dt.NewRow();
            row["ItemName"] = "总收入";
            row["TotalAmount"] = Amount.ToString("C2");
            dt.Rows.Add(row);
            foreach (string key in dictAmount.Keys)
            {
                if (key.Contains("收入"))
                {
                    row = dt.NewRow();
                    row["ItemName"] = "          " + key;
                    row["TotalAmount"] = dictAmount[key].ToString("C2");
                    dt.Rows.Add(row);
                }
            }

            row = dt.NewRow();
            row["ItemName"] = "总支出";
            row["TotalAmount"] = CostAmount.ToString("C2");
            dt.Rows.Add(row);
            foreach (string key in dictAmount.Keys)
            {
                if (key.Contains("支出") || key.Contains("成本"))
                {
                    row = dt.NewRow();
                    row["ItemName"] = "          " + key;
                    row["TotalAmount"] = dictAmount[key].ToString("C2");
                    dt.Rows.Add(row);
                }
            }

            row = dt.NewRow();
            row["ItemName"] = "利润";
            row["TotalAmount"] = Profit.ToString("C2");
            dt.Rows.Add(row);
            row = dt.NewRow();
            row["ItemName"] = "利润率";
            row["TotalAmount"] = ProfitRate.ToString("P2");
            dt.Rows.Add(row); 
            #endregion

            this.winGridView2.DataSource = dt.DefaultView;
            this.winGridView2.PrintTitle = Portal.gc.gAppUnit + " -- " + "经营情况分析报表";
        }

        private void BindTradeDetail()
        {
            #region 添加别名解析
            this.winGridView3.AddColumnAlias("CreateDate", "日期");
            this.winGridView3.AddColumnAlias("ItemName", "项目名称");
            this.winGridView3.AddColumnAlias("Amount", "金额");
            this.winGridView3.AddColumnAlias("Creator", "经手人");
            #endregion

            DataGridViewRow row;
            for (int i = 0; i < winGridView2.dataGridView1.SelectedRows.Count; i++)
            {
                row = winGridView2.dataGridView1.SelectedRows[i];
                string ItemName = row.Cells["ItemName"].Value.ToString().Trim();
                if (!string.IsNullOrEmpty(ItemName))
                {
                    this.winGridView3.PrintTitle = Portal.gc.gAppUnit + " -- " + string.Format("经营情况[{0}]账务明细", ItemName);
                    this.winGridView3.DisplayColumns = "CreateDate,ItemName,Amount,Creator";

                    DataTable dt = Portal.gc.CreateTable("CreateDate,ItemName,Amount,Creator").Tables[0];
                    
                    #region 计算相关的内容

                    #region 销售收入
                    if (ItemName == "客房 销售收入")
                    {
                        dt = BLLFactory<RoomBill>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    }
                    else if (ItemName == "茶室 销售收入")
                    {
                        dt = BLLFactory<TeaSuiteBill>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    }
                    else if (ItemName == "KTV 销售收入")
                    {
                        dt = BLLFactory<KTVSuiteBill>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    } 
                    #endregion

                    #region 销售成本
                    else if (ItemName == "客房 销售成本")
                    {
                        dt = BLLFactory<RoomBill>.Instance.GetTradeCostDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    }
                    else if (ItemName == "茶室 销售成本")
                    {
                        dt = BLLFactory<TeaSuiteBill>.Instance.GetTradeCostDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    }
                    else if (ItemName == "KTV 销售成本")
                    {
                        dt = BLLFactory<KTVSuiteBill>.Instance.GetTradeCostDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value);
                    } 
                    #endregion

                    #region 采购支出
                    else if (ItemName == "客房仓库采购支出")
                    {
                        dt = BLLFactory<PurchaseHeader>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, "客房仓库");
                    }
                    else if (ItemName == "茶室仓库采购支出")
                    {
                        dt = BLLFactory<PurchaseHeader>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, "茶室仓库");
                    }
                    else if (ItemName == "KTV仓库采购支出")
                    {
                        dt = BLLFactory<PurchaseHeader>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, "KTV仓库");
                    } 
                    #endregion

                    #region 其他收入与支出
                    else if (ItemName == "客房 其他收入")
                    {
                        dt = BLLFactory<OtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, true);
                    }

                    else if (ItemName == "茶室 其他收入")
                    {
                        dt = BLLFactory<TeaOtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, true);
                    }
                    else if (ItemName == "KTV 其他收入")
                    {
                        dt = BLLFactory<KTVOtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, true);
                    }

                    else if (ItemName == "客房 其他支出")
                    {
                        dt = BLLFactory<OtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, false);
                    }

                    else if (ItemName == "茶室 其他支出")
                    {
                        dt = BLLFactory<TeaOtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, false);
                    }
                    else if (ItemName == "KTV 其他支出")
                    {
                        dt = BLLFactory<KTVOtherIncome>.Instance.GetTradeDetail(this.dtTradeStart.Value, this.dtTradeEnd.Value, false);
                    }  
                    #endregion
                    
                    #endregion

                    #region 汇总金额
                    decimal amount = 0M;
                    foreach (DataRow dr in dt.Rows)
                    {
                        amount += Convert.ToDecimal(dr["Amount"].ToString());
                    }
                    dt.Rows.Add(dt.NewRow());
                    dt.Rows.Add(dt.NewRow());

                    DataRow myRow = dt.NewRow();
                    myRow["Amount"] = amount.ToString();
                    dt.Rows.Add(myRow); 
                    #endregion

                    this.winGridView3.DataSource = dt.DefaultView;
                }

                break;
            }
        }

        private void btnTradeSearch_Click(object sender, EventArgs e)
        {
            BindTradeData();
        }

        private void txtDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindTradeData();
        }
    }
}
